package reading.data;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import reading.common.CommonUtil;
import reading.common.enums.CodeEnumUtil;
import reading.common.enums.IBaseEnum;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Create by txw on 2017/11/8
 * Description: 枚举处理拦截  数据库存储int, 页面显示中文
 * DataSourceMap:
 *
 * @author txw
 **/
public class EnumTypeHandler<E extends Enum<?> & IBaseEnum> extends BaseTypeHandler<IBaseEnum> {
    private Class<E> clazz;

    public EnumTypeHandler(Class<E> enumType) {
        if (enumType == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }

        this.clazz = enumType;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, IBaseEnum parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
        return getEnum(s);
    }

    private E getEnum(String s) {
        int i = -1;
        //判断数据库为数字或中文
        if (!CommonUtil.isNullAndNullStr(s)) {
            s = s.trim();
            //数字
            if (CommonUtil.isNumeric(s)) {
                i = Integer.parseInt(s);
            } else {
                return CodeEnumUtil.stringOf(clazz, s);
            }
        }
        return CodeEnumUtil.codeOf(clazz, i);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
        return getEnum(s);
    }


    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String s = cs.getString(columnIndex);
        return getEnum(s);
    }
}
